from fastapi import APIRouter, Request, HTTPException, Header

from backend.const import *
from backend.error import error_pydantic_msg
from backend.exception import ValueMissError
from backend.handler import (
    HandleAnalysisAlgorithm, 
    HandleAnalysisSearch, 
    HandleAnalysisExecute, 
    HandleAnalysisStatus, 
    HandleAnalysisCallback,
)
from backend.model import *
from common.response import OkResponse, BadRequestResponse, ServerErrorResponse


router = APIRouter()


@router.get("/algorithm")
def analysis_algorithm():
    try:
        return OkResponse(data=HandleAnalysisAlgorithm())
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))
    

@router.post("/search")
async def analysis_search(post_body: PostBodyAnalysisSearch):
    print(type(post_body), post_body)
    try:
        data = await HandleAnalysisSearch(post_body)
        return OkResponse(data=data)
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))
    

@router.post("/execute")
async def analysis_execute(post_body: PostBodyAnalysisExecute):
    print(type(post_body), post_body)
    try:
        data = await HandleAnalysisExecute(post_body)
        return OkResponse(data=data)
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))
    

@router.get("/status")
def analysis_async_status(job_id: str):
    '''本接口用于查询异步运行任务的状态
    '''
    try:
        return OkResponse(data=HandleAnalysisStatus(job_id))
    except ValueMissError as e:
        return BadRequestResponse(data=repr(e))
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))
    

@router.get("/callback")
def analysis_async_callback(job_id: str):
    '''本接口用于分析结果的回调，可同时处理search搜索结果和execute密态分析结果的异步返回
    '''
    try:
        return OkResponse(data=HandleAnalysisCallback(job_id))
    except ValueMissError as e:
        return BadRequestResponse(data=repr(e))
    except ValidationError as e:
        return ServerErrorResponse(data=error_pydantic_msg(e))
    except Exception as e:
        return ServerErrorResponse(data=repr(e))
    